﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows.Input;
using Socium.Domain.Collections;

namespace Socium.Presentation {
	public abstract class IndexViewModelBase<TModel, TChild> : PageViewModel {
		protected IndexViewModelBase(string display_name, TModel model, IEnumerable<TChild> childeren) : base(display_name) {
			DisplayName = display_name;
			_model = model;

			_childeren.CollectionChanged += OnCollectionChanged;
			_childeren.AddRange(childeren);

			NewItemCommand = new Command(() => OnNewChild(model));
		}

		protected IndexViewModelBase(string display_name, TModel model) : this(display_name, model, Enumerable.Empty<TChild>()) {}

		#region Model

		readonly TModel _model;

		public TModel Model {
			get { return _model; }
		}

		#endregion

		#region Childeren

		readonly ObservableCollection<TChild> _childeren = new ObservableCollection<TChild>();

		public ICollection<TChild> Childeren {
			get { return _childeren; }
		}

		void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
			var old_items = e.OldItems;
			if (old_items != null) {
				foreach (TChild old_item in old_items) {
					OnItemRemoved(Model, old_item);
				}
			}

			var new_items = e.NewItems;
			if (new_items != null) {
				foreach (TChild new_item in new_items) {
					OnItemAdded(Model, new_item);
				}
			}
		}

		#endregion

		protected virtual void OnItemAdded(TModel model, TChild child) {}
		protected virtual void OnItemRemoved(TModel model, TChild child) {}

		public ICommand NewItemCommand { get; private set; }
		protected abstract void OnNewChild(TModel model);
		
		public bool IsEmpty {
			get { return _childeren.Count == 0; }
		}
	}
}
